// Copyright (c) 2010 god6or@gmail.com under MIT license.

package ul.ownet

import ul.comm.{OneWire, OneWireThermometer, OneWire18B20, OneWire18S20}

object Sensor {
    // sensor information string format (Serial, Type, Name, Temperature, Correction)
    val fmtStr = "%6s   %10s   %20s   %6s   %12s"
} 

class Sensor(
    val typeCode: Int,
    val serialNumber: Long,
    var portName: String,              // communication port name
    var name: String = "",             // sensor name
    var selected: Boolean = false,     // selection flag
    var correction: Double = 0.0,      // temperature correction value
    var alarmMin: Double = Double.NaN, // minimum value
    var alarmMax: Double = Double.NaN  // maximum value
 ) {
    // 1-wire thermometer instance
    val sensor: OneWireThermometer = typeCode match {
        case OneWire.types.DS18B20 => new OneWire18B20( serialNumber )
        case OneWire.types.DS18S20 => new OneWire18S20( serialNumber )
        case _ => null
    }
    def serialNumberHex = sensor.serialNumberHex
    
    // get/set temperature
    def temperature = if (!sensor.temperature.isNaN) (sensor.temperature + correction) else Double.NaN;
    def temperature_= (t: Double) = { sensor.temperature = if (!t.isNaN) (t - correction) else Double.NaN };
    var lastTemperature = Double.NaN

    def rdData	( ow: OneWire ): Boolean = sensor.rdData(ow)
    def wrData( ow: OneWire ): Boolean = sensor.wrData(ow)
    def startConversion( ow: OneWire ): Boolean = sensor.startConversion(ow)
    
    /// compares this sensor with other's type and serial
    def equalsTo( other: Sensor ) = sensor.equalsTo( other.sensor )
    /// copies internal data of this sensor to other sensor
    def copyTo( other: Sensor ): Unit = {
        other.portName = portName
        other.name = name
        other.selected = selected
        other.correction = correction
    }
    
    /// generate configuration string
    override def toString: String = {
        "" + portName + ";" + name + ";" + typeCode + ";" + serialNumber + ";" +
        selected + ";" + correction
    }
    /// generate list string
    def toListString = format( Sensor.fmtStr,
        sensor.serialNumberHex,
        sensor.typeName,
        name,
        if (temperature.isNaN) "-" else format("%6.2f", temperature),
        format("%12.2f",correction)
    )
}

